import os
# from cgi import logfile
import matplotlib.pyplot as plt
import datetime
from log import Logger
from common import data_preprocessing
from xgboost import  XGBClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import   roc_auc_score
import joblib
from sklearn.preprocessing import StandardScaler



plt.rcParams['font.family'] = 'SimHei'
plt.rcParams['font.size'] = 15

class Attrition_model:
    #初始化属性
    def __init__(self,path):
        logfile_name = 'train_' + datetime.datetime.now().strftime('%Y%m%d%H%M%S')
        self.logfile = Logger('./',logfile_name).get_logger()
        self.logfile.info('开始创建人才流失模型的对象啦')
        self.data_source = data_preprocessing(path)
def ana_data(data,logger):
    ana_data = data.copy()
    # print(ana_data.head(10))
    # fig = plt.figure(figsize=(20,30))
    # ax1 = fig.add_subplot(511)

    # plt.grid(True)
    # ax1.set_title('年龄对人才流失的影响')
    # ax1.set_xlabel('年龄')
    # plt.show()




def model_train(data,logger):
    x = data.iloc[:,1:]
    y = data['Attrition']
    # print(x)
    x_train,x_test,y_train,y_test = train_test_split(x,y,test_size=0.2,random_state=25,stratify=y)
    #标准化
    transfer = StandardScaler()
    x_train = transfer.fit_transform(x_train)
    x_test  = transfer.transform(x_test)
    # #定义超参字典
    # param_dict={
    #     'n_estimators':[50,100,150,200],
    #     'max_depth':[3,5,6,7],
    #     'learning_rate':[0.01,0.1]
    # }
    #
    # # xgboost模型
    # es = XGBRegressor()
    # # 创建网格搜索
    # gs_es = GridSearchCV(es,param_grid=param_dict,cv=5)
    # #模型训练
    # gs_es.fit(x_train,y_train)
    #打印最优超惨组合
    # logger.info(f'最优参数组合:{gs_es.best_params_}')

    es = XGBClassifier(learning_rate= 0.1, max_depth=3, n_estimators= 50)
    es.fit(x_train,y_train)

    y_pre = es.predict_proba(x_test)[:,1]

    print(f"预测值：{y_pre}")
    # print(f'分类评估报告{classification_report(y_test, y_pre)}')
    # print(f'准确率{accuracy_score(y_test, y_pre)}')
    # print(f'混淆矩阵{confusion_matrix(y_test, y_pre)}')
    my_roc_auc_score = roc_auc_score(y_test,y_pre)
    print(f'auc值{my_roc_auc_score}')
    # 模型保存
    # joblib.dump(es, "Attrition_xgb.pkl")
    # logger.info(f"模型保存成功，保存路径{os.path.abspath("Attrition_xgb.pkl")}")


if __name__ == '__main__':
    at = Attrition_model('../../data/raw/train.csv')
    ana_data(at.data_source, at.logfile)
    model_train(at.data_source,at.logfile)
